//
//  YZPublishCommunityVC.m
//  VET
//
//  Created by YZ on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZPublishCommunityVC.h"
#import "YZPublishCommunityViewModel.h"
#import "YZMainNavigationController.h"
#import "YZPublishCommunityContentCell.h"
#import "YZPublishCommunityFunctionCell.h"
#import "YZActionSheet.h"
#import "YZCommunityLocationVC.h"
#import "YZCameraVC.h"
#import "YZVideoVC.h"
#import "TZImagePickerController.h"
#import "YZVideoPreVC.h"


typedef NS_ENUM(NSInteger,YZMediaType) {
    YZMediaTypeNone = 111,
    YZMediaTypePhoto,
    YZMediaTypeVideo
};

@interface YZPublishCommunityVC ()<UITableViewDelegate,UITableViewDataSource,YZActionSheetDelegate,YZPublishCommunityContentCellDelegate,YZCommunityLocationVCDelegate,YZMediaProtocol,YZVideoPreVCDelegate>

@property (nonatomic, strong) UITableView *contentTb;

@property (nonatomic, strong) YZPublishCommunityViewModel *viewModel;

@property (nonatomic, strong) YZActionSheet *visableSheet;

@property (nonatomic, assign) YZMediaType  currentMediaTpye;

@property (nonatomic, strong) UIButton *publishBtn;

@end

@implementation YZPublishCommunityVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.currentMediaTpye = YZMediaTypeNone;
    [self configUI];
    [self initUI];
    [self addObserver];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
    [self.viewModel startRequestCommunityLocating];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
    [self.viewModel stopRequestCommunityLocating];
}

#pragma mark -- priviate

- (void)configUI
{
    ((YZMainNavigationController *)self.navigationController).popBlock = ^{
        NSLog(@"back");
    };
    self.view.backgroundColor = kColorWithHex(0xFFFFFF);
    self.title = @"发圈子";
    
    UIButton *publishBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kCurrentDeviceNum(40), kCurrentDeviceNum(20))];
    self.publishBtn = publishBtn;
    [publishBtn setTitle:@"发布" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(publishBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:publishBtn];
}

- (void)initUI
{
    [self.view addSubview:self.contentTb];
}

- (void)publishBtnClicked:(UIButton *)btn
{
    YZWeakSelf(self)
    [self.viewModel publishCommunitySuccess:^(NSObject *obj) {
        [weakself.navigationController popViewControllerAnimated:YES];
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        [SVProgressHUD dismissWithDelay:2.0f];
    } fail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"发布失败"];
        [SVProgressHUD dismissWithDelay:2.0f];
    }];
}

- (void)addObserver
{
    [RACObserve(((YZPublishCommunityContentModel *)[self.viewModel modelInSection:0 row:0]), contentText) subscribeNext:^(NSString *  _Nullable x) {
        [self.publishBtn setTitleColor:x.length == 0 ? [UIColor lightGrayColor] :kColorWithHex(0x32BE60) forState:UIControlStateNormal];
    }];
    
    [RACObserve(self.viewModel, loading) subscribeNext:^(id  _Nullable x) {
        if ([x boolValue]) {
            [SVProgressHUD show];
        }else
        {
            [SVProgressHUD dismiss];
        }
    }];
}
#pragma mark -- YZVideoPreVCDelegate

- (void)deleteCurrentVideoAssert
{
    self.viewModel.currentVideoAssertInfo = nil;
    [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark -- YZMediaProtocol

- (void)getCurrentVideoAssert:(PHAsset *)assert andUrl:(NSURL *)url andCurrentOrientation:(AVCaptureVideoOrientation)orientation
{
    if (!assert) return;
    self.viewModel.currentVideoAssertInfo = @{@"assert":assert,@"url":url};
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    });
    self.viewModel.videoOrientation = orientation;
}

- (void)getCurrentPhotoAssert:(PHAsset *)assert
{
    if (!assert) return;
    NSMutableArray *asserts = [NSMutableArray arrayWithArray:self.viewModel.selectedAssets];
    [asserts addObject:assert];
    self.viewModel.selectedAssets = asserts;
    NSMutableArray *photos = [NSMutableArray arrayWithArray:self.viewModel.selectedPhotos];
    [[TZImageManager manager] getOriginalPhotoWithAsset:assert completion:^(UIImage *photo, NSDictionary *info) {
        if (photo) {
            [photos addObject:photo];
            self.viewModel.selectedPhotos = photos;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        });
    }];
}

#pragma mark - TZImagePickerController
- (void)toPhotoAlbum
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:3 delegate:nil pushPhotoPickerVc:YES];
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    // 1.设置目前已经选中的图片数组
    imagePickerVc.selectedAssets = self.viewModel.selectedAssets; // 目前已经选中的图片数组
    //在内部显示拍照按钮
    imagePickerVc.allowTakePicture = NO;
    //在内部显示拍视频按钮
    imagePickerVc.allowTakeVideo = NO;
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
//    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
//        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//    }];
    //3.设置是否可以选择视频/图片/原
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    //是否可以多选视频
    imagePickerVc.allowPickingMultipleVideo = NO;
    //4.照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    //设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
#pragma mark - 到这里为止
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.viewModel.selectedPhotos = photos;
        self.viewModel.selectedAssets = assets;
        [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self  presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.viewModel.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.dataSource[section].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if(indexPath.section == 0)
    {
        static NSString *cellId = @"YZPublishCommunityContentCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if(!cell){
            cell = [[YZPublishCommunityContentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        ((YZPublishCommunityContentCell *)cell).model = [self.viewModel modelInSection:indexPath.section row:indexPath.row];
        ((YZPublishCommunityContentCell *)cell).delegate = self;
    }else
    {
        static NSString *cellId = @"YZPublishCommunityFunctionCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if(!cell){
            cell = [[YZPublishCommunityFunctionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        ((YZPublishCommunityFunctionCell *)cell).model = [self.viewModel modelInSection:indexPath.section row:indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        [self.view endEditing:YES];
        if(indexPath.row == 0){
            YZCommunityLocationVC *locationVC = [NSClassFromString(@"YZCommunityLocationVC") new];
            self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:nil action:nil];
            [locationVC setValue:[self.viewModel getCommunityLocattion] forKey:@"currentLocation"];
            locationVC.delegate = self;
            locationVC.currentAddressName = [[self.viewModel modelInSection:1 row:0] valueForKey:@"title"];
            [self.navigationController pushViewController:locationVC animated:YES];
        }else
        {
            self.visableSheet = [[YZActionSheet alloc] initWithTitle:@"" sheetTitles:@[@"公开",@"我的好友"] cancleBtnTitle:@"取消" sheetStyle:YZActionSheetLeftTextAndRightImg delegate:self];
            self.visableSheet.selectedIndex = [((YZPublishCommunityFunctionModel *)[self.viewModel modelInSection:1 row:1]).selectTitle isEqualToString:@"公开"] ? 0 :1;
            [self.visableSheet show];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return UITableViewAutomaticDimension;
    }
    return 44;
}

#pragma mark -- YZCommunityLocationVC

- (void)didSelectedLocationItem:(id)item
{
    YZPublishCommunityFunctionModel *model = (YZPublishCommunityFunctionModel *)[self.viewModel modelInSection:1 row:0];
    model.title = [item valueForKey:@"addressName"];
    model.selectTitle = @"";
    model.logo = @"ico_lbs_active";
    model.normal = NO;
    [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark -- YZActionSheetDelegate

- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex
{
    //selected
    if ([actionSheet isEqual:self.visableSheet]) {
        YZPublishCommunityFunctionModel *model = (YZPublishCommunityFunctionModel *)[self.viewModel modelInSection:1 row:1];
        model.selectTitle = buttonIndex == 0 ? @"公开":@"我的好友";
        model.normal = NO;
        model.logo = @"ico_lbs_active";
        [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }else
    {
        if (self.currentMediaTpye == YZMediaTypeNone) {
            switch (buttonIndex) {
                case 0:
                {
                    self.currentMediaTpye = YZMediaTypePhoto;
                    [self toPhotoAlbum];
                    break;
                }
                case 1:
                {
                    self.currentMediaTpye = YZMediaTypePhoto;
                    YZCameraVC *cameraVC = [YZCameraVC new];
                    cameraVC.delegate = self;
                    [self presentViewController:cameraVC animated:YES completion:nil];
                    break;
                }
                case 2:
                {
                    self.currentMediaTpye = YZMediaTypeVideo;
                    YZVideoVC *videoVC = [YZVideoVC new];
                    videoVC.delegate = self;
                    [self presentViewController:videoVC animated:YES completion:nil];
                    break;
                }
                default:
                    break;
            }
        }else if(self.currentMediaTpye == YZMediaTypePhoto)
        {
            switch (buttonIndex) {
                case 0:
                {
                    [self toPhotoAlbum];
                    break;
                }
                case 1:
                {
                    YZCameraVC *cameraVC = [YZCameraVC new];
                    cameraVC.delegate = self;
                    [self presentViewController:cameraVC animated:YES completion:nil];
                    break;
                }
                default:
                    break;
            }
        }else
        {
            YZVideoVC *videoVC = [YZVideoVC new];
            videoVC.delegate = self;
            [self presentViewController:videoVC animated:YES completion:nil];
        }
    }
}

- (void)actionSheetCancle:(YZActionSheet *)actionSheet
{
    //cancel
}

#pragma mark -- YZPublishCommunityContentCellDelegate

- (void)communityContentCell:(id)cell imgItemDidSelectedIndex:(NSInteger)index
{
    NSMutableArray * photoModels = [NSMutableArray arrayWithCapacity:self.viewModel.selectedPhotos.count];
    for (int i =0 ; i < self.viewModel.selectedPhotos.count; i++) {
        TZAssetModel *model = [[TZAssetModel alloc] init];
        model.cachedImage = self.viewModel.selectedPhotos[i];
        [photoModels addObject:model];
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self.viewModel.selectedAssets selectedPhotos:self.viewModel.selectedPhotos photoModels:photoModels index:index];
    imagePickerVc.maxImagesCount = 9;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.isSelectOriginalPhoto = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.viewModel.selectedPhotos = photos;
        self.viewModel.selectedAssets = assets;
        [self.contentTb reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)communityContentCell:(id)cell videoItemDidSelectedIndex:(NSInteger)index
{
    YZPublishCommunityVideoModel *videoModel = ((YZPublishCommunityContentModel *)[self.viewModel modelInSection:0 row:index]).imgs.firstObject;
    YZVideoPreVC *vc = [[YZVideoPreVC alloc] init];
    vc.delegate = self;
    TZAssetModel *model = [TZAssetModel modelWithAsset:videoModel.assert type:TZAssetModelMediaTypeVideo timeLength:@""];
    vc.model = model;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)communityContentCellAddItemSelected
{
    if (self.currentMediaTpye == YZMediaTypePhoto)
    {
        if (((YZPublishCommunityContentModel *)[self.viewModel modelsInSection:0].firstObject).imgs.count == 1) {
            self.currentMediaTpye = YZMediaTypeNone;
        }
    }else if(self.currentMediaTpye == YZMediaTypeVideo)
    {
        if ([((YZPublishCommunityContentModel *)[self.viewModel modelsInSection:0].firstObject).imgs.lastObject isKindOfClass:[YZPublishCommunityImgModel class]]) {
            self.currentMediaTpye = YZMediaTypeNone;
        }
    }
    
    NSArray *arr = nil;
    if (self.currentMediaTpye == YZMediaTypeNone) {
        arr = @[@"相册",@"拍照",@"小视频"];
    }else if(self.currentMediaTpye == YZMediaTypePhoto)
    {
        arr = @[@"相册",@"拍照"];
    }else
    {
        arr = @[@"小视频"];
    }
    [self.view endEditing:YES];
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:@"" sheetTitles:arr cancleBtnTitle:@"取消" sheetStyle:YZActionSheetLeftTextAndRightImg delegate:self];
    [sheet show];
}

#pragma mark -- setters && getters

- (UITableView *)contentTb
{
    if(!_contentTb){
        _contentTb = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - (kStatusBarHeight + YZ_BOTTOM_MARGIN + kTopViewHeight)) style:UITableViewStylePlain];
        _contentTb.estimatedRowHeight = 300;
        _contentTb.tableFooterView = [UIView new];
        _contentTb.delegate = self;
        _contentTb.dataSource = self;
    }
    return _contentTb;
}

- (YZPublishCommunityViewModel *)viewModel
{
    if(!_viewModel){
        _viewModel = [YZPublishCommunityViewModel new];
    }
    return _viewModel;
}
@end
